package thread;
//wait锁竞争
public class ThreadDemo24 {
    public static void main(String[] args) {
        Object locker = new Object();
        Thread t1 = new Thread(()->{
            synchronized (locker){
                System.out.println("t1 wait 之前");//1.t1执行之后立即拿到锁
                try {
                    locker.wait();//2.释放锁进入堵塞
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("t1 wait 之后");//5.被唤醒后可能进入阻塞状态(锁竞争),然后重新拿到锁
            }
        });
        Thread t2 = new Thread(()->{
            try {
                Thread.sleep(5000);//确保让t1先拿到锁
                synchronized (locker){//3.t2拿到锁
                    System.out.println("t2 notify 之前");
                    locker.notify();//4.唤醒t1并且执行完此线程中的代码块,执行完之后释放锁
                    System.out.println("t2 notify 之后");
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });
        t1.start();
        t2.start();
        //执行结果
        //t1 wait 之前
        //t2 notify 之前
        //t2 notify 之后
        //t1 wait 之后

    }
}
